<template>
    <view>
		<u-navbar
			title="数据展示"
			@rightClick="rightClick"
			:placeholder="true"
			:autoBack="true"
		>
		</u-navbar>
		<div>
			<u--text type="info" text="设备数据" :bold="true" size="24px"></u--text>
			<u-grid
			        :border="false"
			        @click="click"
					col="2"
			>
			    <u-grid-item
			            v-for="(baseListItem,baseListIndex) in baseList"
			            :key="baseListIndex"
			    >
			        <u-icon
			                :customStyle="{paddingTop:50+'rpx'}"
			                :name="baseListItem.name"
			                :size="45"
			        ></u-icon>
			        <text class="grid-text">{{baseListItem.title}}</text>
					<text class="grid-text">{{baseListItem.value}}</text>
			    </u-grid-item>
			</u-grid>
			<u-toast ref="uToast" />
			<u-gap height="20" bgColor="#3c9cff"></u-gap>
			<u-grid
			        :border="false"
			        @click="click"
					col="1"
			>
			    <u-grid-item>
			        <text style="font-size: 24px; color: #909399;padding: 10rpx 0 20rpx 0rpx;">{{formattedTime}}</text>
			    </u-grid-item>
			</u-grid>
		</div>
		
		
    </view>
</template>

<script>
	import mqtt from 'mqtt/dist/mqtt.js'
    export default {
        data() {
            return {
                baseList: [
					{
						name: 'checkmark-circle-fill',
						title: '温度',
						value: '22.3℃'
                    },
                    {
                        name: 'bell-fill',
                        title: '湿度',
						value: '45%RH'
                    },
                ],
				formattedTime:'',
				options: {
					connectTimeout: 4000, //超时时间
					clientId: "k0y6kf1oJGF.ANDRUIDAPP|securemode=2,signmethod=hmacsha256,timestamp=1711032768123|", //id
					username: "ANDRUIDAPP&k0y6kf1oJGF", //用户名
					password: "2504b96965d3cf0ae6813c56b2b9cdc0ed89facd514c7a76dccc234b2c58e221", //密码
					cleanSession: false,
					keepAlive: 300,//心跳值，心跳值太大可能会连接不成功，这个参考文档
				},
				region: "cn-shanghai",
				instanceId: "iot-06z00a79o1y2aqz"
            }
        },
		created() {
			console.log("created")
		    this.getDateTime()
			this.connectMqtt()
		    },
        methods: {
            click(name) {
                this.$refs.uToast.success(`点击了第${name}个`)
            },
			rightClick() {
				console.log('rightClick');
			},
			getDateTime() {
				const now = new Date();
				const year = now.getFullYear();
				const month = ('0' + (now.getMonth() + 1)).slice(-2);
				const day = ('0' + now.getDate()).slice(-2);
				const hours = ('0' + now.getHours()).slice(-2);
				const minutes = ('0' + now.getMinutes()).slice(-2);
				const seconds = ('0' + now.getSeconds()).slice(-2);
				this.formattedTime = year + '年' + month + '月' + day + '日' + hours + ':' + minutes + ':' + seconds;
			},
			// mqtt链接
			connectMqtt () {
				
				// #ifdef H5
				console.log("H5")
				var client = mqtt.connect(
				      "ws://k0y6kf1oJGF.iot-as-mqtt.cn-shanghai.aliyuncs.com:443",//上面在文档中的连接域名
				      this.options
				    );
				// #endif
				// #ifdef MP-WEIXIN||APP-PLUS
				console.log("APP")
				var client = mqtt.connect(
				      "wx://k0y6kf1oJGF.iot-as-mqtt.cn-shanghai.aliyuncs.com:443",//上面在文档中的连接域名
				      this.options
				    );
				// #endif
				client.on("connect", (e) => {
					console.log("连接成功");
					client.subscribe(
					  "/sys/k0y6kf1oJGF/ANDRUIDAPP/thing/service/property/set",//这里是订阅的主题，这里参考我给的链接
					  { qos: 0 },
					  (error) => {
						console.log(error);
					  }
					);
				}).on('reconnect', function() {
					console.log('on reconnect')
				});
				client.on("error", (error) => {
				  console.log("连接出错", error);
				});
				client.on("message", (topic, message) => {
				  console.log('接收消息:',message.toString());
				  var data = JSON.parse(message.toString())
				  var temp_humi_data = data["items"]
				  //console.log("数据：", temp_humi_data)
				  var temp = temp_humi_data["temp"]
				  var humi = temp_humi_data["humi"]
				  console.log("温度：", temp["value"])
				  console.log("湿度：", humi["value"])
				   //this.$set(this.baseList[0]["value"],‘name’,‘张三’)
				  this.baseList[0]["value"] = temp["value"].toString() + "℃"
				  this.baseList[1]["value"] = humi["value"].toString() + "%RH"
				  //this.$forceUpdate(); // 刷新组件
				});
			},


        }
    }
</script>

<style lang="scss">
    .grid-text {
        font-size: 18px;
        color: #909399;
        padding: 10rpx 0 20rpx 0rpx;
        /* #ifndef APP-PLUS */
        box-sizing: border-box;
        /* #endif */
    }
</style>